package com.lezhi.socialgram.scheduling;

import com.lezhi.socialgram.mapper.moments.MomentMapper;
import com.lezhi.socialgram.model.moments.Moment;
import com.lezhi.socialgram.util.TableUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;


/**
 * Created by daizhen on 2017/4/1.
 */
@Component
public class TableSchedule {

    private static final Logger logger = LoggerFactory.getLogger(TableSchedule.class);

    @Autowired
    MomentMapper momentMapper;

    @Scheduled(fixedDelay = 1000 * 60 * 60 * 12)
    public void momentsTableSchedule() {

        //获取下周的表名
        String table = TableUtils.getTableNameWithDate(Moment.class, TableUtils.WeekOption.PLUS).getTableName();
        Calendar now = Calendar.getInstance();
        //按周日划分建表，如果是周六就新建下周的表
        if (now.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
            logger.info("周六到了，创建下周要用的表");
            try {
                logger.info(table + "已经存在了,无需创建");
            } catch (Exception e) {
                if (e.getMessage().indexOf("exist") >= 0) {
                    momentMapper.createMomentsTable(table);
                }
            }
        }

    }
}